/**
 * 订单核心数据概览
 * @author hanzhichen (hanzhichen@baijia.com)
 * @date 2021-03-02
 */

import {useState, useCallback, useEffect} from 'react';
import {usePersistFn, useRequest} from 'ahooks';
import moment from 'moment';
import {Card} from 'antd';
import {querySelectOptions, queryValues} from '~/service/refundReport';
import SearchForm from '../../common/CommonSearchBar';
import {
    convertSearcherParams,
    formatRangePickerValue,
    addDashBoardIdToDimensionAndValues
} from '../../common/utils';
import OrderOfflineChartCard from './OrderOfflineChartCard';
import {searchFormCfg, dashBoardsCfg, selectUnitId} from './config';

// 设置默认时间
const initValues = {
    // eslint-disable-next-line no-magic-numbers
    // originPaidDay: moment(),
    // // eslint-disable-next-line babel/camelcase
    // teacher_nickname: 'cccc',
    // // eslint-disable-next-line babel/camelcase
    // clazz_number: 'aaaa'
};
const formItemLayout = {
    labelCol: {span: 6},
    wrapperCol: {span: 18}
};
const tailLayout = {
    wrapperCol: {span: 24}
};

const formatDateSearchValueToDate = formatRangePickerValue('YYYYMMDD');
const formatDateSearchValueToTime = formatRangePickerValue('YYYY-MM-DD HH:mm');

const OrderOfflineChart = props => {
    // searchform
    // 查询按钮的loading
    const [loading, setLoading] = useState(false);
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});

    // 将searchForm返回的值转化为后端需要的格式
    const convertParams = usePersistFn(params => {
        // 转换参数
        const {originPaidDay, ...rest} = params || {};
        let newSearcherParams = params;
        if (originPaidDay == null) {
            newSearcherParams = rest;
        } else {
            const rangeToday = [
                moment(originPaidDay).startOf('day'),
                moment(originPaidDay).endOf('day')
            ];
            const formattedPayDate = formatDateSearchValueToDate(rangeToday);
            const formattedPayTime = formatDateSearchValueToTime(rangeToday);
            newSearcherParams = {
                dt: formattedPayDate,
                // eslint-disable-next-line babel/camelcase
                paid_time: formattedPayTime,
                ...rest
            };
        }
        const queryParams = convertSearcherParams(newSearcherParams);
        return queryParams;
    });

    // 缓存查询参数中的表单部分
    const [dimensionAndValues, setDimensionAndValues] = useState(
        convertParams(initValues)
    );

    // chart查询方法
    const {
        data: data1,
        loading: loading1,
        run: run1,
        refresh: refresh1,
    } = useRequest(queryValues, {
        manual: true,
        formatResult(res) {
            const {data: resData} = res || {};
            return resData;
        }
    });

    const [chartData, setChartData] = useState();

    useEffect(() => {
        setChartData(data1);
    }, [data1]);

    useEffect(() => {
        setLoading(loading1);
    }, [loading1]);

    /** 点击搜索按钮 */
    const handleSearch = useCallback(params => {
        const queryParams = convertParams(params);
        setDimensionAndValues(queryParams);
        const params1 = {
            dashBoardList: [dashBoardsCfg[0]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                queryParams,
                dashBoardsCfg[0].dashBoardId
            ),
        };
        run1(params1);
    }, []);

    /** 点击重置按钮 */
    const handleReset = useCallback(() => {
        const queryParams = convertParams(initValues);
        setDimensionAndValues(queryParams);
        setChartData();
    }, []);

    // 请求单个表单配置项
    const handleFetchOptions = useCallback(
        ({
            key,
            searchKey,
            pager,
            dependItemKey,
            dependItemValue,
            isGetingMore,
            options: curOptions,
            fieldsValue
        }) => {
            let permissions = [];
            searchFormCfg.forEach(item => {
                if (item.key === 'originPaidDay') {
                    // const originPaidDay = fieldsValue[item.key];
                    // if (originPaidDay) {
                    //     const rangeToday = [
                    //         moment(originPaidDay).startOf('day'),
                    //         moment(originPaidDay).endOf('day')
                    //     ];
                    //     const formattedPayDate = formatDateSearchValueToDate(
                    //         rangeToday
                    //     );
                    //     const formattedPayTime = formatDateSearchValueToTime(
                    //         rangeToday
                    //     );
                    //     permissions.push({
                    //         dimensionId: `${selectUnitId}_dt`,
                    //         dimensionName: 'dt',
                    //         filterItems: formattedPayDate
                    //     });
                    //     permissions.push({
                    //         dimensionId: `${selectUnitId}_paid_time`,
                    //         dimensionName: 'paid_time',
                    //         filterItems: formattedPayTime
                    //     });
                    // }
                } else {
                    permissions.push({
                        dimensionId: `${selectUnitId}_${item.key}`,
                        dimensionName: item.key,
                        filterItems: Array.isArray(fieldsValue[item.key])
                            ? fieldsValue[item.key]
                            : fieldsValue[item.key] == null
                                ? []
                                : [fieldsValue[item.key]]
                    });
                }
            });

            permissions = permissions.filter(item => item.filterItems?.length);

            const params = {
                pager,
                dimensionId: `${selectUnitId}_${key}`,
                dimensionName: key,
                searchKey,
                permissions,
                unitId: selectUnitId
            };

            querySelectOptions(params).then(res => {
                const {data, pager} = res;
                let options =
                    data.map(item => ({
                        key: item,
                        value: item,
                        label: item
                    })) || [];
                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }
                setSelectOptions({key, options, pager});
            });
        },
        []
    );

    return (
        <Card title="订单离线数据" className="special-class-order-offline">
            <SearchForm
                noCache
                formItemLayout={formItemLayout}
                tailLayout={tailLayout}
                labelAlign="left"
                config={searchFormCfg}
                selectOptions={selectOptions}
                initialValues={initValues}
                onOk={handleSearch}
                onReset={handleReset}
                onfetchOptions={handleFetchOptions}
                loading={loading}
            />
            <OrderOfflineChartCard
                data={chartData}
                loading={loading1}
                dashBoard={dashBoardsCfg[0]}
                dimensionAndValues={dimensionAndValues}
                unitId={dashBoardsCfg[0].unitId}
            />
        </Card>
    );
};

export default OrderOfflineChart;
